//
//  PhotoBrowserViewController.swift
//  JJWeibo
//
//  Created by JJ on 15/9/14.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit
import SVProgressHUD

private let JJPhotoBrowserCellID="JJPhotoBrowserCellID"

class PhotoBrowserViewController: UIViewController {
    
    var urls:[NSURL]
    var indexPath:NSIndexPath
    var photoScale:CGFloat?
    
    var currentImageIndex:NSIndexPath{
        
        return collectionView.indexPathsForVisibleItems().last!
    }
    
    var currentView:UIImageView{
        
        let cell=collectionView.cellForItemAtIndexPath(currentImageIndex) as! PhotoBrowserCell
        
        return cell.imageView
    }
    
    init(urls:[NSURL],indexPath:NSIndexPath){
        self.urls=urls
        self.indexPath=indexPath
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    override func viewDidLoad() {

        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        pageControl.currentPage = indexPath.item
    }

    override func loadView() {
        
        var rec=UIScreen.mainScreen().bounds
        rec.size.width += 20
        view=UIView(frame:rec)
        view.backgroundColor=UIColor.blackColor()
        setUI()
    }
    
    private func hiddController(ishidden:Bool){
        pageControl.hidden = ishidden
        saveButton.hidden=ishidden
        closeButton.hidden=ishidden
        view.backgroundColor = ishidden ? UIColor.clearColor() : UIColor.blackColor()
        collectionView.backgroundColor = view.backgroundColor

    }
    
    private func setUI(){
        view.addSubview(collectionView)
        collectionView.frame = view.bounds
        
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        view.addSubview(pageControl)
        
        saveButton.translatesAutoresizingMaskIntoConstraints=false
        closeButton.translatesAutoresizingMaskIntoConstraints=false
        pageControl.translatesAutoresizingMaskIntoConstraints=false
        
        let viewDic=["sb":saveButton,"cb":closeButton]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[sb(80)]-(>=100)-[cb(80)]-28-|", options: [], metrics: nil, views: viewDic))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[sb(35)]-8-|", options: [], metrics: nil, views: viewDic))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[cb(35)]-8-|", options: [], metrics: nil, views: viewDic))
        
        view.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -8))

        closeButton.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { [weak self](btn) -> Void in
            self?.dismissViewControllerAnimated(true, completion: nil)
        }
        
        saveButton.rac_signalForControlEvents(.TouchUpInside).subscribeNext { [weak self](btn) -> Void in
          self?.savePhoto()
        }
        
        pageControl.rac_signalForControlEvents(.ValueChanged).subscribeNext { [weak self](pageControl) -> Void in
            
            self?.pageChange()
        }

         prepareCollectionView()
         preparePageControl()
    }
    private func pageChange(){
        
        let indexPath=NSIndexPath(forItem: pageControl.currentPage, inSection: 0)
        
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    private func savePhoto(){
        
        guard let image = currentView.image else{
            
            SVProgressHUD.showErrorWithStatus("木有图像")
            return
        }
        
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        
    }
    
    
    @objc private func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject ){
        let message = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showInfoWithStatus(message)
    }
    
    private func preparePageControl(){
        
        pageControl.numberOfPages = urls.count
        pageControl.hidesForSinglePage=true
        pageControl.pageIndicatorTintColor=UIColor.whiteColor()
        pageControl.currentPageIndicatorTintColor=UIColor.greenColor()
    }
    
    private func prepareCollectionView(){
        
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: JJPhotoBrowserCellID)
        collectionView.dataSource=self
        collectionView.delegate=self
        
        let layout=collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize=view.bounds.size
        
        layout.minimumInteritemSpacing=0
        layout.minimumLineSpacing=0
        layout.scrollDirection=UICollectionViewScrollDirection.Horizontal
        collectionView.pagingEnabled=true
        
    }
    
    private lazy var collectionView:UICollectionView=UICollectionView(frame:CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    
    private lazy var saveButton:UIButton=UIButton(titil: "保存", fontSize: 14)
    
    private lazy var closeButton:UIButton=UIButton(titil: "关闭", fontSize: 14)
    
    private lazy var pageControl=UIPageControl()
    
}

extension PhotoBrowserViewController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        pageControl.currentPage = collectionView.indexPathsForVisibleItems().last?.item ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell=collectionView.dequeueReusableCellWithReuseIdentifier(JJPhotoBrowserCellID, forIndexPath: indexPath) as! PhotoBrowserCell
//        cell.backgroundColor=UIColor.randomColor()
        cell.url=urls[indexPath.item]
        cell.PhotoBrowserDelegate=self
        return cell
    }
}
extension PhotoBrowserViewController:PhotoBrowserCellDelegate{
    
    func photoBrowserCellDidZoom(scale: CGFloat) {
        
        photoScale=scale
        
        hiddController(scale<1.0)
        
        if scale < 1.0{
            startInteractiveTransition(self)
        }else{
            
            view.transform=CGAffineTransformIdentity
            view.alpha=1.0
        }
        
    }
    
    func photoBrowserCellEndZoom() {
        if photoScale < 0.8 {
            completeTransition(true)
            
        }else{
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                
                self.view.transform = CGAffineTransformIdentity
                self.view.alpha = 1.0
                }, completion: { (_) in
                    self.hiddController(false)
            })
        }
    }
}

extension PhotoBrowserViewController:UIViewControllerInteractiveTransitioning{
    
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        view.alpha=photoScale!
        view.transform=CGAffineTransformMakeScale(photoScale!, photoScale!)
    }
}

extension PhotoBrowserViewController: UIViewControllerContextTransitioning {
    
    /// 完成转场
    func completeTransition(didComplete: Bool) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 容器视图
    func containerView() -> UIView? { return view.superview }
    
    func isAnimated() -> Bool { return true }
    func isInteractive() -> Bool { return true }
    func transitionWasCancelled() -> Bool { return false }
    func presentationStyle() -> UIModalPresentationStyle { return UIModalPresentationStyle.Custom }
    
    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition() {}
    func cancelInteractiveTransition() {}
    
    func viewControllerForKey(key: String) -> UIViewController? { return nil }
    func viewForKey(key: String) -> UIView? { return nil }
    func targetTransform() -> CGAffineTransform { return CGAffineTransformIdentity }
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
    func finalFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
}





